<template>
    <a-menu
        theme="dark"
        mode="inline"
        @openChange="onOpenChange"
        :openKeys="openKeys"
        @select="onSelect"
        :selectedKeys="selectedKeys"
    >
        <template v-for="item in treeData" :key="item.key">
            <template v-if="!item.children">
                <a-menu-item :key="item.key">
                    <component :is="$Icon[item.icon]" />
                    <span>{{ item.title }}</span>
                </a-menu-item>
            </template>
            <template v-else>
                <NavSubMenu :datas="item" :key="item.key" />
            </template>
        </template>
    </a-menu>
</template>

<script lang="ts" setup>
import { ref, defineProps, withDefaults, defineEmits, defineExpose } from 'vue'
import { NavMenuTree } from '@/utils/NavMenuTree';
import { SysMenuDto } from '@/models/System/SysMenuDto';
import NavSubMenu from '@/components/NavMenu/NavSubMenu.vue';



/**
 * 属性参数
 */
interface IProps {
    /**
     * 菜单数据
     */
    datas: SysMenuDto.Base[],

    /**
     * 默认打开
     */
    opend?: []
}

const props = withDefaults(defineProps<IProps>(), {
    opend: () => []
});


const emits = defineEmits(["onSelect"]);


let tree = NavMenuTree.toJson(props.datas, 0);
let rootKey = NavMenuTree.getRootKey(tree);

const treeData = ref<SysMenuDto.NavMenuJson[]>(tree);

const selectedKeys = ref<number[]>([]);
const openKeys = ref<number[]>([]);




/**
 * 打开
 */
const onOpenChange = (key: number[]) => {
    if (key.length > 1) {
        openKeys.value = [key[key.length - 1]];
        return;
    }
    if (key.length == 1) {
        openKeys.value = [key[0]];
        return;
    }
};

const onSelect = (item: any) => {
    let data = props.datas.find(f => f.id == item.key);
    emits("onSelect", data);

    selectedKeys.value = item.selectedKeys;
    localStorage.setItem("_NavMenuKeyPath", JSON.stringify(item.keyPath));
    localStorage.setItem("_NavMenuSelectedKeys", JSON.stringify(item.selectedKeys));
    //console.log("菜单选中");
}

const InitOpenKeys = () => {
    let keyPath = localStorage.getItem("_NavMenuKeyPath");
    let keys: any = localStorage.getItem("_NavMenuSelectedKeys");
    if (keyPath !== undefined && keyPath != "" && keyPath != null) {
        openKeys.value = JSON.parse(keyPath);
        selectedKeys.value = JSON.parse(keys);
    }
}

InitOpenKeys();

/**
 * 对外开放方法
 */
const selected = (id: number) => {
    selectedKeys.value = [id];
    let pids = NavMenuTree.getParentKey(props.datas, id);
    openKeys.value = pids;
};

defineExpose({
    selected
})


</script>